#!/usr/bin/env python
# -*- coding: utf-8 -*-

import urllib2
import re
from hashlib import md5
from hashlib import sha1
from logger import log, fytionException

FetionConfigURL = "http://nav.fetion.com.cn/nav/getsystemconfig.aspx"
FetionConfigXML = """<config><user mobile-no="%s" /><client type="PC" version="%s" platform="W6.1" /><servers version="0" /><service-no version="0" /><parameters version="0" /><hints version="0" /><http-applications version="0" /><client-config version="0" /><services version="0" /><banners version="0" /></config>"""

class ssi():
	def __init__(self, fytion, opener):
		self._opener = opener
		self._fytion = fytion
	
	def get_system_config(self, phone='13910000000'):
		global FetionConfigURL
		global FetionConfigXML

		log("Get system config...")
		url = FetionConfigURL
		body = FetionConfigXML % (phone, self._fytion.FetionVer)
		headers = {'User-Agent':'IIC4.0/PC %s' % self._fytion.FetionVer,'Content-Type': 'application/oct-stream'}
		
		f = self._opener.open(urllib2.Request(url, headers=headers, data=body))
		config_data = f.read()
		
		sipc_url = re.search("<ssi-app-sign-in-v2>(.*)</ssi-app-sign-in-v2>",config_data).group(1)
		sipc_proxy = re.search("<sipc-proxy>(.*)</sipc-proxy>",config_data).group(1)
		http_tunnel = re.search("<http-tunnel>(.*)</http-tunnel>",config_data).group(1)
		
		return {'url': sipc_url, 'proxy': sipc_proxy, 'http_tunnel': http_tunnel}
	
	def get_uri(self, url, phone, passwd):
		log("Get user config...")
		url = url+"?mobileno="+phone+"&domains=fetion.com.cn%3bm161.com.cn%3bwww.ikuwa.cn&v4digest-type=1&v4digest="+sha1("fetion.com.cn:"+passwd).hexdigest()
		headers = {'User-Agent':'IIC4.0/PC %s' % self._fytion.FetionVer,'Content-Type': 'application/oct-stream'}
		
		f = self._opener.open(urllib2.Request(url, headers=headers, data=""))
		
		header = str(f.info())
		body   = f.read()
		try:
			ssic = re.search("ssic=(.+?);",header).group(1)
			sid  = re.search("sip:(.+?)@",body).group(1)
			uri  = re.search('uri="(.+?)" mobile-no',body).group(1)
			user_id = re.search('user-id="(.+?)"',body).group(1)
			status = re.search('user-status="(\d+)"',body).group(1)
		except:
			return False
	
		return {'fetion_id': sid, 'phone': phone, 'passwd': passwd, 'uri': uri, 'ssic': ssic, 'user_id': user_id}
	
